package com.xw.bo.ks.util;

import lombok.extern.slf4j.Slf4j;

import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串的一些工具类
 * @author： XW -> ~
 * @create： 2023/12/4 16:33
 */
@Slf4j
public class BoStringUtils {

    /**
     * 驼峰命名转下划线
     * @param str 例如：createUsername
     * @return 例如：create_username
     */
    public static String cameToUnderline(String str) {
        Matcher matcher = Pattern.compile("[A-Z]").matcher(str);
        StringBuilder builder = new StringBuilder(str);
        int index = 0;
        while (matcher.find()) {
            builder.replace(matcher.start() + index, matcher.end() + index, "_" + matcher.group().toLowerCase());
            index++;
        }
        if (builder.charAt(0) == '_') {
            builder.deleteCharAt(0);
        }
        return builder.toString();
    }

    /**
     * 长度是36个，有数字和小写字母组成，加上-符号
     * @return
     */
    public static String getUuidDefault(){
        UUID uuid = UUID.randomUUID();
        return uuid.toString();
    }

    /**
     * 获取32位的UUID
     * @return 32位字符
     */
    public static String getUUID(){
        String uuid = getUuidDefault();

        return uuid.replaceAll("-","");
    }

    public static Long toLong(String longValue){
        return toLong(longValue,-1L);
    }

    public static Long toLong(String longValue,Long defaultLong){
        try {
            return Long.valueOf(longValue);
        }catch (NumberFormatException numberFormatException){
            log.error("字符串转int失败");
        }
        return defaultLong;
    }

    public static Integer toInt(String intValue){
        return toInt(intValue,-1);
    }


    public static Integer toInt(String intValue,Integer defaultInt){
        try {
            return Integer.valueOf(intValue);
        }catch (NumberFormatException numberFormatException){
            log.error("字符串转int失败");
        }
        return defaultInt;
    }

    public static void main(String[] args) {
        String uuid = BoStringUtils.getUUID();
        log.info("length = {},UUID = {}", uuid.length(),uuid);
    }



}
